package com.yamaha.bikedesalon;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.PauseOnScrollListener;
import com.yamaha.bikedesalon.postItem.Item;
import com.yamaha.bikedesalon.postItem.ViewType;
import com.yamaha.bikedesalon.util.API;
import com.yamaha.bikedesalon.util.AlertDialogManager;

public class YourFeedFragment extends Fragment
		implements
			View.OnClickListener,
			OnItemClickListener {

	private LayoutInflater inflater;
	private View view;

	private ImageLoader imageLoader;

	private final AlertDialogManager dialogManager = new AlertDialogManager();
	private final static AsyncHttpClient client = new AsyncHttpClient();
	private final FeedItemAdapter adapter = new FeedItemAdapter();

	public List<Item> items = new ArrayList<Item>();
	public boolean isFiltered = false;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		this.inflater = inflater;
		view = inflater.inflate(R.layout.feeds_page, container, false);

		return view;
	}

	@Override
	public void onStart() {
		super.onStart();

		// imageLoader = ((MainActivity) getActivity()).getImageLoader();

		final ListView listView = (ListView) view.findViewById(R.id.feed_list);
		listView.setAdapter(adapter);

		boolean pauseOnScroll = true; // or true
		boolean pauseOnFling = true; // or false
		PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, pauseOnScroll, pauseOnFling);
		listView.setOnScrollListener(listener);

		listView.setOnItemClickListener(this);

		adapter.setLoading(true);

		// this.doLoadFromWebApi();

		if (!isFiltered) {
			// Start Loading from WebAPI
			this.doLoadFromWebApi();
		} else {
			adapter.setLoading(false);
			adapter.notifyDataSetChanged();
			isFiltered = false;
		}

	}

	private void doLoadFromWebApi() {
		final String Url = API.SHOW_POST;

		final RequestParams params = new RequestParams();
		// params.put("user_id", SCStaticFunc.getUserId());

		client.post(Url, params, new AsyncHttpResponseHandler() {

			@Override
			public void onStart() {
			}

			@Override
			public void onSuccess(final String response) {

				Log.v("Response", response);
				try {

					final JSONObject obj = new JSONObject(response);

					if (obj.getBoolean("success")) {

						final JSONArray list = obj.getJSONArray("message");

						items = DataManager.ConvertToPostItems(imageLoader, "", list);

						// Notify to Adapter to update values
						adapter.setLoading(false);
						adapter.notifyDataSetChanged();

					} else {
						final String msg = obj.getString("message");
						dialogManager.showAlertDialog(getActivity(), getString(R.string.error_title), msg, true);
					}

				} catch (JSONException e) {
					Log.e(API.SHOW_POST + " Success", e.getMessage(), e);
				}

			}

			@Override
			public void onFailure(Throwable e, String error) {
				Log.e(API.SHOW_POST, error, e);

				final AlertDialogManager manager = new AlertDialogManager();
				manager.showAlertDialog(getActivity(), "Error", error, true);
			}

			@Override
			public void onFinish() {
			}
		});
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {

		if (position < items.size()) {
			if (items.get(position).getViewType() == ViewType.HEADER.ordinal() || items.get(position).getViewType() == ViewType.FOOTER.ordinal()) {
				return;
			}

			final JSONObject info = items.get(position).getObject();

			// final MainActivity mainActivity = (MainActivity) getActivity();
			//
			// // SCStaticFunc.setData(SCStaticFunc.POST_DETAIL, info);
			// mainActivity.showFragment(MainActivity.POST_DETAIL, true);
		}
	}
	@Override
	public void onClick(View v) {
		// final MainActivity mainActivity = (MainActivity) getActivity();

		/*
		 * switch (v.getId()) { case R.id.button_write_on_wall: { postDialog =
		 * new Dialog(getActivity(),
		 * android.R.style.Theme_Translucent_NoTitleBar);
		 * postDialog.setContentView(R.layout.poststatus_layout);
		 * postDialog.show();
		 * 
		 * // Show Keyboard postDialog.getWindow().setSoftInputMode(
		 * WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
		 * 
		 * final ImageButton imageButton = (ImageButton) postDialog
		 * .findViewById(R.id.button_post_img);
		 * imageButton.setOnClickListener(this); } break; case
		 * R.id.button_post_img: { Log.d("SelectionFragment",
		 * "cameraButton Cannot"); handleShowPictureChoosen(); } break; case
		 * R.id.picture_camera_button: {
		 * 
		 * handleCameraAction(); } break; case R.id.picture_gallery_button: {
		 * handlePictureAction(); } break; case R.id.button_your_feed: {
		 * 
		 * } break; case R.id.button_new_feed: {
		 * mainActivity.showFragment(MainActivity.NEW_FEED, false); } break; }
		 */
	}

	// -------------------------------------- Sub Class
	// --------------------------------------

	// private static class ItemHolder {
	// ImageView icon;
	// TextView title;
	// TextView postTime;
	// TextView description;
	// TextView feed_description;
	// ImageView feedImage;
	// }

	private final class FeedItemAdapter extends BaseAdapter {

		private boolean isLoading = true;

		public void setLoading(boolean isLoading) {
			this.isLoading = isLoading;
		}

		@Override
		public int getViewTypeCount() {
			return ViewType.values().length;
		}

		@Override
		public int getCount() {

			if (isLoading) {
				return 1;
			} else {
				return items.size();

			}
		}

		@Override
		public Object getItem(int position) {
			// return items.get(position);
			if (this.isLoading) {
				return null;
			} else {
				return items.get(position);
			}
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public int getItemViewType(int position) {
			if (isLoading) {
				return 1;
			} else {
				return items.get(position).getViewType();
			}
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			final int LOADING_VIEW_ID = 0x2012;
			if (isLoading) {
				convertView = inflater.inflate(R.layout.loading_item, parent, false);
				convertView.setId(LOADING_VIEW_ID);
				return convertView;
			}

			if (convertView != null && convertView.getId() == LOADING_VIEW_ID) {
				convertView = null;
			}

			return items.get(position).getView(inflater, convertView, position);

			// ItemHolder holder;
			// if (convertView == null) {
			// convertView = inflater.inflate(R.layout.feed_item_layout,
			// parent, false);
			// convertView.setId(0x2033 + position);
			//
			// holder = new ItemHolder();
			// holder.description = (TextView) convertView
			// .findViewById(R.id.feed_description);
			// holder.postTime = (TextView) convertView
			// .findViewById(R.id.feed_post_time);
			// holder.feedImage = (ImageView) convertView
			// .findViewById(R.id.feed_item_image);
			// holder.icon = (ImageView) convertView
			// .findViewById(R.id.feed_profile_image);
			// holder.title = (TextView) convertView
			// .findViewById(R.id.feed_title);
			//
			// convertView.setTag(holder);
			// } else {
			// holder = (ItemHolder) convertView.getTag();
			//
			// }
			// // change bg
			// if (position % 2 == 0) {
			// // change bg
			// convertView.setBackgroundResource(R.drawable.new_post_cell_bg1);
			// } else {
			// convertView.setBackgroundResource(R.drawable.new_post_cell_bg2);
			// }
			//
			// // fill each data
			// try {
			// final JSONObject eachItem = items.get(position);
			// if (eachItem.getJSONArray("model_pix") == null) {
			// holder.feedImage.setVisibility(View.GONE);
			// } else {
			// String firstImg = eachItem.getJSONArray("model_pix")
			// .getString(0);
			// imageLoader.displayImage(firstImg, holder.feedImage);
			// }
			//
			// final String icon = eachItem.getString("icon");
			// if (icon == null || icon.length() == 0) {
			// holder.icon.setImageBitmap(null);
			// } else {
			// imageLoader.displayImage(icon, holder.icon);
			// }
			//
			// holder.title.setText(eachItem.getString("title"));
			// holder.description.setText(eachItem.getString("description"));
			//
			// } catch (Exception e) {
			// e.printStackTrace();
			// }

			// return convertView;

		}
	}

}
